package com.qicheng.wlhyspider.anhui.service;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qicheng.wlhyspider.anhui.dao.AhCompanyRepository;
import com.qicheng.wlhyspider.anhui.entity.AhCompanyEntity;
import com.qicheng.wlhyspider.common.Constants;
import com.qicheng.wlhyspider.common.PageResult;
import com.qicheng.wlhyspider.common.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AhCompanyService {
    private final AhCompanyRepository ahCompanyRepository;
    private final RedisUtils redisUtils;

    public AhCompanyService(AhCompanyRepository ahCompanyRepository, RedisUtils redisUtils) {
        this.ahCompanyRepository = ahCompanyRepository;
        this.redisUtils = redisUtils;
    }

    public String save() {
        String url = String.format("https://wlhy.ahyg.com.cn/basis/company/list?page=%s&limit=%s", 1, 10000);
        Object o = redisUtils.get(Constants.AH_TOKEN);
        HttpResponse httpResponse = HttpUtil.createGet(url)
                .header("x-auth-token", o + "")
                .execute();

        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            PageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), PageResult.class);
            PageResult.ResultDTO result = pageResult.getResult();
            List<AhCompanyEntity> list = JSONArray.parseArray(JSONArray.toJSONString(result.getRecords()), AhCompanyEntity.class);
            if (CollectionUtils.isEmpty(list)) {
                throw new RuntimeException("查询失败");
            } else {
                AhCompanyEntity ahCompanyEntity = list.get(0);
                ahCompanyRepository.save(ahCompanyEntity);
                return ahCompanyEntity.getId();
            }
        } else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
            throw new RuntimeException("登录信息失效");
        } else {
            log.info("查询失败");
            throw new RuntimeException("查询失败");
        }
    }
}
